import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('保存用户设置SP的使用'),
        ),
        body: Center(child: SPWidget()),
      ),
    );
  }
}

class SPWidget extends StatefulWidget {
  @override
  _SPWidgetState createState() => _SPWidgetState();
}

class _SPWidgetState extends State<SPWidget> {
  int _counter;

  @override
  void initState() {
    super.initState();
    _getSP().then((sp) {
      int spCounter = sp.getInt('counter') ?? 0;
      setState(() {
        _counter = spCounter;
      });
    });
  }

  Future<SharedPreferences> _getSP() async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    return sp;
  }

  _addNum() async {
    SharedPreferences sp = await _getSP();
    setState(() {
      _counter++;
    });
    // 保存数据到sp
    await sp.setInt('counter', _counter);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('$_counter'),
        RaisedButton(
          child: Text('add'),
          onPressed: _addNum,
        )
      ],
    );
  }
}
